/**
 * Meituan.com Inc.
 * Copyright (c) 2010-2018 All Rights Reserved.
 */

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.concurrent.TimeUnit;

/**
 * <p></p>
 *
 * @author tuyou@meituan.com
 * @version v0.1 2018-11-06 6:29 PM tuyou Exp $$
 */
public class MainTest {

    public static void main(String[] args) throws Exception {

        LoadingCache<String, String> objectCache = CacheBuilder.newBuilder()
                //同时写缓存的县城城
                .concurrencyLevel(8)
                //写入后多久缓存失效
                .expireAfterWrite(1, TimeUnit.SECONDS)
                .expireAfterAccess(1, TimeUnit.SECONDS)
                //设置缓存容量
                .initialCapacity(10).maximumSize(100)
                //设置要统计缓存的命中率
                .recordStats()
                //设置缓存移除监听器
                .removalListener(removalNotification -> {
                    System.out.println(removalNotification.getKey() + " was removed, cause is :" + removalNotification.getCause());
                })
                .build(new CacheLoader<String, String>() {
                    @Override
                    public String load(String key) throws Exception {
                        System.out.println("load data:" + key);
                        String value = key + ":cache-value";
                        return value;
                    }
                })
//                .build()
                ;

        objectCache.put("tuyou", "涂有");
        objectCache.put("yangrui", "杨瑞");

        System.out.println(objectCache.get("tuyou"));

        Thread.sleep(2000);
        System.out.println(objectCache.get("tuyou"));

        objectCache.invalidate("tuyou"); //主动删除缓存
        System.out.println(objectCache.get("tuyou"));
    }
}